package com.CampusForum.community.service.impl;



import com.CampusForum.community.dao.MessageMapper;
import com.CampusForum.community.entity.Message;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.service.MessageService;
import com.CampusForum.community.util.HostHolder;
import com.CampusForum.community.util.SensitiveFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    /**
     * 获取总的会话数量
     */
    @Override
    public int getTotalRows(int userId) {
        return messageMapper.getConversationCount(userId);
    }

    /**
     * 获取该页的所有会话
     */
    @Override
    public List<Message> getConversations(int id, int offset, int limit) {
        return messageMapper.getConversations(id, offset, limit);
    }

    @Override
    public int getLetterUnreadCount(int id, String conversationId) {

        return messageMapper.getLetterUnreadCount(id, conversationId);
    }

    @Override
    public int getLetterCount(String conversationId) {
        return messageMapper.getLetterCount(conversationId);
    }

    @Override
    public List<Message> getLetters(String conversationId, int offset, int limit) {
        return messageMapper.getLetters(conversationId, offset, limit);
    }

    @Override
    public int insertMessage(int to_id, String content) {
        Message message = new Message();
        User fromUser = hostHolder.getUser();
        int from_id = fromUser.getId();
        message.setFromId(from_id);
        message.setToId(to_id);
        String conversationId;
        if (from_id > to_id) {
            conversationId = to_id + "_" + from_id;
        } else {
            conversationId = from_id + "_" + to_id;
        }
        message.setConversationId(conversationId);
        String htmlEscape = HtmlUtils.htmlEscape(content);
        String filter = sensitiveFilter.filter(htmlEscape);
        message.setContent(filter);
        message.setStatus(0);
        message.setCreateTime(new Date());
        int count = messageMapper.insertMessage(message);
        return count;
    }
}
